<?php
	defined('_JEXEC') or die('Restricted access');
	require_once(CUTEENGINE_BASE_ACTION_PATH."base_action_class.php");
    require_once(CUTEENGINE_BASE_STEP_PATH."base_step_class.php");
	//
    // t_action_set_values_from_db
    //
	class t_action_set_values_from_db extends t_base_action
	{
        // property declaration
		// protected        
		const language_position_last = 1;
		// D
        protected $db_fields = array();
		// P
        protected $page_fields = array();

		// property declaration
		// public
		// P
        const proper_properties_position_per_SQL = 0;
        const proper_properties_position_per_condition_values = 1;
        const proper_properties_position_per_db_fields = 2;
        const proper_properties_position_per_page_fields = 3;        
		const proper_properties_position_per_results_count = 4;        
        const proper_properties_position_last = 5;

        // R
        const required_fields_count = 4;
        // method declaration
    	// protected
        // G
		static function get_help_proper_property($a_index)
		{
			$local_return = 'NO HELP AVAILABLE';
			/*switch ($a_index) 
            {
                case self::proper_properties_position_:
					$local_return = '';
				break;                
			}*/
			return $local_return;
		}
        static function get_default_proper_property($a_index)
		{
			$local_return = '';
			//echo "a_index: $a_index<br>";
			switch ($a_index) 
            {
				case self::proper_properties_position_per_SQL:
					$local_return = '';
				break;
 				case self::proper_properties_position_per_condition_values:
					$local_return = '';
				break;
                case self::proper_properties_position_per_db_fields:
					$local_return = '';
				break;  
				case self::proper_properties_position_per_page_fields:
					$local_return = '';
				break;	
				case self::proper_properties_position_per_results_count:
					$local_return = '10';
				break;			
			}
			return $local_return;
		}
        protected function get_proper_properties_position_last()
        {
            return self::proper_properties_position_last;
        }
		protected function get_required_fields_count()
        {
            return self::required_fields_count;
        }
        

		// I
        protected function initialize_action()
        {		

			if (! $this->initialized)
			{
                parent::initialize_action();
				// db_fields
				$this->db_fields = $this->proper_properties_array[self::proper_properties_position_per_db_fields];
				//echo "print_r(this->db_fields): ". print_r($this->db_fields); echo "<br>";	
				// page_fields
				$this->page_fields = $this->proper_properties_array[self::proper_properties_position_per_page_fields];
		
				//$this->initialized = true;
			}
			return $this->initialized;
		}		
        protected function initialize_step_execution()
        {		
            global $g_cuteengine;
            //echo "initialize_steps_execution ".$this->get_action_name()."<BR>";
            // STEPS
			$local_step = $this->steps_list[$this->current_step_index];
			$local_index = $this->current_step_index;
			if (isset($local_step))
			{
				$local_step->initialize();
				$local_class = get_class($local_step);  
				
				//
							 
				if ($local_index === t_base_action::step_result)
				{
					//echo "custom execute<br>";
					$this->custom_execute_step($local_step);                        
					
					
				}    
				else
				{
					$this->execute_step($local_step);                                            
				}
			}    
		}	
        protected function custom_execute_step($a_step)        
        {
            //echo __METHOD__."<BR>";
            $local_component = $this->parent_component;
            $local_next_step = $this->steps_list[$this->current_step_index + 1];
			$local_field = $a_step->field;
            if (isset($local_field))
			{
				$local_field_class = get_class($local_field);
				$local_start_tag = $local_field->get_start_tag();
				$local_result_tag = $local_field->get_result_tag();				
			}	
            $local_class = get_class($a_step);
            //echo "custom_execute_step - action_name:" . $this->get_action_name() ." - a_step: ".$a_step->name."($local_class) - local_field: ".$local_field->name."<BR>";
           
                    
			switch ($local_class) 
            {
	
                /*********** t_step_set_ce_tag_content ***********/
                case t_step_set_ce_tag_content:
                    $local_action_event = $this->get_first_parent_action_class("t_action_set_event_part");
                    if ($local_action_event != null)
                    {
                        //echo "SI t_action_set_event_part parent(".$this->get_action_name().")";
                        if (!$this->parent_part->has_parent_part())
                            $a_step->code .="
        ".$this->get_content_loader_code($local_next_step->code);
                        else
                            $a_step->code .= $local_next_step->code;
                    }
                    else
                    {
						//echo "NO t_action_set_event_part parent";
                        //ob_start();                   
                        try
                        {
                            
                            $this->do_action_from_ajax();
                            //$local_content = ob_get_contents();
                            //$local_result_tag->set_text_to_include(trim($local_content)); 
                            
                        }
                        catch (Exception $e) 
                        {
                            $g_cuteengine->log->add_log_error($e->getMessage());
                        } 
                        //ob_end_clean();
						//echo $local_content;
                    }    
                   
                break;    
				/*********** t_step_ajax_put **********
                case t_step_ajax_put:
					if ($local_field_class == t_field_grid)
					{
						
						$a_step->code = "this.html_tag(\"".$local_result_tag->name."\").innerHTML = a_response_text; ";
					}
					else
					{
						$a_step->code = "var local_resp = new Function(a_response_text)(); ";
						foreach ($this->page_fields as $local_field_index => $local_field) 
						{
							$a_step->code .="this.html_tag(\"".$this->page_fields[$local_field_index]."\").value = local_resp[\"".$this->page_fields[$local_field_index]."\"]; ";
						}
						$a_step->code .= $local_next_step->code;
					}
                break;   */             
            }
            //echo "custom_execute_step OK <BR>";
        }
        // method declaration
    	// public
        public function __construct($a_parent_component,$a_parent_part,$a_common_properties_str, $a_proper_properties_str) 
		{
			//echo "a_proper_properties_str: $a_proper_properties_str<br>";
            parent::__construct($a_parent_component,$a_parent_part,$a_common_properties_str, $a_proper_properties_str);
          //  echo "count:".count($this->fields_list);
			// steps
            if ($this->parent_part->has_parent_part())
            {
               // echo "1 - this->get_action_name():". $this->get_action_name()."<br>";
                /*  step_start  */   
                $this->steps_list[t_base_action::step_start] = t_base_step::create_step_from_string('|t_step_ajax_start|'.$this->get_action_name().'_start|'.
                    $this->fields_list[t_base_action::step_result].'|'); ;
                
                /*  step_criteria  */   
                $this->steps_list[t_base_action::step_criteria] = t_base_step::create_step_from_string('|t_step_ajax_get|'.$this->get_action_name().'_criteria|'.
                    $this->fields_list[t_base_action::step_result].'|'); 
                
                /*  step_result  */   
                //$this->steps_list[t_base_action::step_result] = t_base_step::create_step_from_string('|t_step_ajax_put|'.$this->get_action_name().'_result|'.
                    //$this->fields_list[t_base_action::step_result+1].'|');   
                $this->steps_list[t_base_action::step_result] = t_base_step::create_step_from_string('|t_step_set_ce_tag_content|'.$this->get_action_name().'_result|'.
                    $this->fields_list[t_base_action::step_result].'|'); 
            }      
            else
            {
                
               // echo "3- this->get_action_name():". $this->get_action_name()."<br>";
                /*  step_start  */   
                $this->steps_list[t_base_action::step_start] = null;
                /*  step_criteria  */   
                $this->steps_list[t_base_action::step_criteria] = null;
                /*  step_result  */   
                $this->steps_list[t_base_action::step_result] = t_base_step::create_step_from_string('|t_step_set_ce_tag_content|'.$this->get_action_name().'_result|'.
                    $this->fields_list[t_base_action::step_result].'|'); 
            }    

			
		}
        // D
		public function do_action_from_ajax()
        {
			global $g_url_parameters_namespace;
            global $g_ambient_namespace;
			//echo "action_name: ".$this->get_action_name()."<br>";
			$local_parameter = parent::do_action_from_ajax();
			if (trim($local_parameter->argument) == '')
				$local_parameter = $g_url_parameters_namespace->get_parameter_by_position(0); 
			//echo "local_parameter->argument: $local_parameter->argument<br>";
			$local_result = new t_content_loader_result;
            $local_string_result = '';
			$local_action_event = $this->get_first_parent_action_class("t_action_set_event_part");
			$local_select_location_query = $this->get_action_name()."_query";
			$local_component = $this->parent_component;
			//echo $this->proper_properties_array[self::proper_properties_position_per_SQL
			//print_r($local_parameter);
			if ($local_parameter->request_type === t_url_parameter::request_type_no_page)
			{
				$local_count = $local_parameter->get_arguments_count();
				echo "local_count: $local_count<br>";
			    $local_from = $local_parameter->get_argument_value($local_count-2);
			    $local_length = $local_parameter->get_argument_value($local_count-1);
			}	
		   // echo "local_from:$local_from<br>";
		    //echo "local_length:$local_length<br>";

			//
			$local_sql = trim($this->proper_properties_array[self::proper_properties_position_per_SQL]);
			//echo "local_sql:$local_sql<br>";
            if (($local_from == '') || ($local_from <0))
                $local_from = 0;
			//echo "this->proper_properties_array[self::proper_properties_position_per_results_count]: ". $this->proper_properties_array[self::proper_properties_position_per_results_count]. "<br>";	
			//print_r($this->proper_properties_array[self::proper_properties_position_per_results_count]);
            if ($local_length == '')
                $local_length = $this->proper_properties_array[self::proper_properties_position_per_results_count];
            if ((strpos($local_sql,':limit_from:')) && (strpos($local_sql,':limit_length:')))
            {
                $local_sql = str_replace(':limit_from:', $local_from,$local_sql);
                $local_sql = str_replace(':limit_length:', $local_length,$local_sql);
            }
            else
            {
                $local_limit = '';
				//echo "strpos(local_sql,'CALL '): ". strpos($local_sql,'CALL ');
				if (($local_length > 0) && (strpos($local_sql,'CALL ') !== 0))
                    $local_limit = " LIMIT $local_from,$local_length";	
                $local_sql = $local_sql.$local_limit;
            }    
			//echo "local_sql:$local_sql<br>";
			//$local_conditions_value = substr($this->proper_properties_array[self::proper_properties_position_per_condition_values],1,-1);
			//echo "local_conditions_value:$local_conditions_value<br>";
			$local_conditions_value_array = $this->proper_properties_array[self::proper_properties_position_per_condition_values];
           // print_r($local_conditions_value_array);
			// NEW QUERY
			$local_component->new_query(
				$local_select_location_query,
				$local_sql,
				$g_ambient_namespace->connection);
			//
			//echo "local_parameter->get_argument_value(2): ". $local_parameter->get_argument_value(2)."<br>";
			$local_query_query = $local_component->get_query(
				$local_select_location_query);
			//$local_query_query->set_value_parameter(
				//$local_parameter->get_argument_value(2),0);
			//SET QUERY CONDITION VALUES
			foreach ($local_conditions_value_array as $local_value_index => $local_value)
			{
				//echo "local_value_index: $local_value_index => local_value: $local_value<br>";
				$local_query_query->set_value_parameter(
					$local_value,$local_value_index);
			}	
		    
			// manage result
			$local_result_step = $this->steps_list[t_base_action::step_result];
			$local_result_field = $local_result_step->field; 
			$local_field_class = get_class($local_result_field);
           
			
            //echo "local_field_class:$local_field_class";
            switch ($local_field_class) 
            {
	
                /*********** t_step_ajax_put ***********/
                case t_field_grid:
                    $local_event_type = null;
					
                    if ($local_action_event != null)
                    {
						
						$local_query_query->execute_function_from_even_with_empty_query_result($local_result_field,
                            'get_tags_structure_from_event',array($local_result,$local_from,$local_length));
                        $local_result->succeeded = true;//$local_query_query->execute_query();
                        if (! $local_result->succeeded)
						{
                            
							$local_result->error_msg = $local_query_query->get_last_error();
						}	
						else
						{
							
							$this->execute_child_ations($local_result,$local_query_query->connection);						
						}	
                        echo $local_result->get_json_string();	

                    }    
                    else
                    {
       					$local_string_result = $local_query_query->execute_function_from_even_with_empty_query_result ($local_result_field,
                            'get_tags_structure',array($local_from,$local_length));
                        //zecho $local_string_result;
						/*if ($local_query_query->query_num_rows() == 0)
							$local_string_result = $local_result_field->get_tags_structure_from_empty_query*/
                    } 
                    if (count($this->parent_part->db_fields) == 0)
						// create db_field array from parent part field
						$local_query_query->execute_function_from_fields_result($this->parent_part,
							'set_db_fields');                    
                break;
				default:
					foreach ($this->db_fields as $local_field_index=>$local_field) 
					{
						if ($a_string_result == '')
						{
							$a_string_result = 'var local_array = [];';
						}	
						$a_string_result .= 'local_array["'.$this->page_fields[$local_field_index].'"] = "'.$a_query_parameter->sql_values[$local_field].'";';
					}				
					if ($a_string_result != '')
					{
						$a_string_result .= ' return local_array;';
						$local_result->add_function_result(
							"","","", $a_string_result); 
						$local_result->succeeded = true;
						$this->execute_child_ations($local_result,$local_query_query->connection);
                        
					}	
					else
					{
						$local_result->succeeded = false;
                        $local_result->error_msg = 'no db_fields found';
					}
                    echo $local_result->get_json_string();	

            }
			$local_query_query->close_all_results();
            //
			
				
		
            
            
        }


		
		public function get_language_position_last()
        {
            return self::language_position_last;
        }
        
		
        
    }
?>    